package cn.haoran.modules.palaeobios.controller;


import cn.haoran.common.utils.PageUtils;
import cn.haoran.common.utils.ResultInfo;
import cn.haoran.modules.palaeobios.entity.Column;
import cn.haoran.modules.palaeobios.service.ColumnService;
import cn.haoran.modules.palaeobios.utils.IndexColumn;
import cn.haoran.modules.sys.controller.AbstractController;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.validation.Valid;
import java.time.LocalDateTime;
import java.util.Arrays;
import java.util.List;
import java.util.Map;

/**
 * <p>
 *  栏目前端控制器
 * </p>
 *
 * @author haoran
 * @since 2019-12-12
 */
@RestController
@RequestMapping("/column")
@Api("栏目接口列表")
public class ColumnController extends AbstractController {
    @Autowired
    private IndexColumn indexColumn;
    private final
    ColumnService columnService;

    @Autowired
    public ColumnController(ColumnService columnService) {
        this.columnService = columnService;
    }

    @GetMapping("/list")
    @ApiOperation("分页列表")
    public ResultInfo list(@RequestParam Map<String, Object> params){
        PageUtils page = columnService.queryPage(params);
        return ResultInfo.ok().put("page",page);
    }
    @PostMapping("save")
    @ApiOperation("保存")
    public ResultInfo save(@RequestBody @Valid Column column){
        column.setCreateDate(LocalDateTime.now());
        column.setCreateId(getUserId());
        column.setCreateName(getUser().getUsername());
        columnService.insert(column);
        return ResultInfo.ok();
    }

    @GetMapping("/info/{id}")
    @ApiOperation("根据id查询")
    public ResultInfo info(@PathVariable("id") Long id){
        Column column = columnService.selectById(id);
        return ResultInfo.ok().put("column",column);
    }
    @PostMapping("/delete")
    @ApiOperation("批量删除或删除")
    public ResultInfo delete(@RequestBody Long[] ids){
        List<Long> list = Arrays.asList(ids);
        for (Long i : list) {
            // 从map里读取id 能得到说明是首页栏目不已删除
            String columName = indexColumn.get(i);
            if (columName ==null){
                columnService.deleteById(i);
            }
        }

        return ResultInfo.ok();
    }
    @PostMapping("/update")
    @ApiOperation("修改信息")
    public ResultInfo update(@RequestBody @Valid Column column){
        columnService.updateById(column);
        return ResultInfo.ok();
    }
}
